#include "sys.h"
#include "log.h"
#include "packet.h"
#include "hook.h"

static struct hook *hook_list = NULL;

int hook_register(hook_init init, hook_fun fun){
    struct hook *hk = malloc(sizeof(struct hook));
    if(!hk){
        log_syserr("new hook error.");
        return 0;
    }
    hk->fun = fun;
    hk->init = init;
    hk->prev = NULL;
    hk->next = NULL;

    if(hook_list == NULL){
        hook_list = hk;
        return 1;
    }else{
        struct hook *ptr = hook_list;
        while(ptr->next)ptr = ptr->next;
        ptr->next = hk;
        hk->prev = ptr;
    }
    return 1;
}

int Hooks_init(int argc, char **argv){
    struct hook *ptr;
    ptr = hook_list;
    while(ptr){
        if(ptr->init){
            ptr->init(argc, argv);
        }
        ptr = ptr->next;
    }
    return 1;
}

int Hook( Packet_t *packet){
    int ret = 0;
    struct hook *ptr, *prev;
    ptr = hook_list;
    while(ptr){
        ret = ptr->fun(packet);
        switch(ret){
            case HOOK_RETURN:
                break;
            case HOOK_REMOVE:
                prev = ptr->prev;
                prev->next = ptr->next;
                free(ptr);
                break;
            default:
                break;
        }
        ptr = ptr->next;
    }
    return 1;
}